package com.ngmaster.socket;

import com.alibaba.fastjson.JSON;
import com.ngmaster.apiserver.config.SocketConfig;
import com.ngmaster.socket.callback.CallbackDefault;
import com.ngmaster.socket.message.QueryDeviceRunInfoMessage;
import com.ngmaster.socket.util.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息处理逻辑
 * */
@Slf4j
@Component
public abstract class MessageHandler<T extends ProtocolMessage> {

    private static MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json;charset=utf-8");

    private String apiUrl = "http://admin.xcs.iotwater.cn/devApi/";

    public String getApiUrl() {
        if (MessageManager.getInstance().getSocketConfig().getWebApiUrl() != null) {
            return MessageManager.getInstance().getSocketConfig().getWebApiUrl();
        }
        return apiUrl;
    }

    public void setApiUrl(String apiUrl) {
        this.apiUrl = apiUrl;
    }

    /**
     * 处理消息
     * */
    public boolean handleMessage(T protocolMessage) {
        protocolMessage.setByteArray(null);
        protocolMessage.setImeiBytes(null);
        String msgJson = JSON.toJSONString(protocolMessage);

        RequestBody requestBody = RequestBody.create(this.getJsonMetaType(), msgJson);
        HttpRequestUtil.asyncPost(this.getApiUrl(), new CallbackDefault(), requestBody);
        log.info("[api:{}] [send post data:{}]", new Object[] {
                this.getApiUrl(), msgJson
        });
        return true;
    }

    protected MediaType getJsonMetaType() {
        return JSON_MEDIA_TYPE;
    }

    public void sendCmdQueryDeviceInfo(ProtocolMessage touchMsg) {
        QueryDeviceRunInfoMessage msg = new QueryDeviceRunInfoMessage();
        msg.setCmd(CmdType.QueryDeviceInfo.getCmd());
        msg.setImei(touchMsg.getImei());
        msg.setByteArray(new ByteArray());
        msg.setDataLength(CmdType.QueryDeviceInfo.getDataLength());
        msg.setState((byte)0x00);
        msg.convertHexImeiToBytes();
        msg.serial();
        NetManager.getInstance().getTerminal(touchMsg.getImei()).sendMessage(msg);
    }
}
